package cn.ultrarisk.scadmin.manager.web.controller.log;

import cn.ultrarisk.scadmin.manager.biz.monitor.entity.ErrorLog;
import cn.ultrarisk.scadmin.manager.biz.monitor.entity.SlowLog;
import cn.ultrarisk.scadmin.manager.biz.monitor.service.ErrorLogService;
import cn.ultrarisk.scadmin.manager.biz.monitor.service.SlowLogService;
import cn.ultrarisk.scadmin.manager.util.IOUtil;
import cn.ultrarisk.scadmin.manager.util.JsonUtil;
import cn.ultrarisk.scadmin.manager.web.controller.BaseController;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

/**
 * LogGatherController
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/6/22
 * @since V1.0
 */
@Controller
@RequestMapping("/log/gather")
public class GatherLogController extends BaseController {

    private Type errorJsonType = new TypeToken<List<ErrorLog>>(){}.getType();
    private Type slowJsonType = new TypeToken<List<SlowLog>>(){}.getType();

    @Autowired
    private ErrorLogService errorLogService;
    @Autowired
    private SlowLogService slowLogService;

    @ResponseBody
    @RequestMapping(value = "/slow", method = RequestMethod.POST)
    public ResponseEntity<String> gatherSlowLog(HttpServletRequest request) throws IOException {
        String json = IOUtil.in2Str(request.getInputStream(), "utf-8");
        List<SlowLog> list = JsonUtil.fromJson(json, slowJsonType);
        slowLogService.create(list);
        return getOkResponseEntity();
    }

    @ResponseBody
    @RequestMapping(value = "/error", method = RequestMethod.POST)
    public ResponseEntity<String> gatherErrorLog(HttpServletRequest request) throws IOException {
        String json = IOUtil.in2Str(request.getInputStream(), "utf-8");
        List<ErrorLog> list = JsonUtil.fromJson(json, errorJsonType);
        errorLogService.create(list);
        return getOkResponseEntity();
    }
}
